<?php

namespace app\admin\controller;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Throwable;
use app\common\controller\Backend;

/**
 * 提交记录
 */
class Info extends Backend
{
    /**
     * Info模型对象
     * @var object
     * @phpstan-var \app\admin\model\Info
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['activity'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Info();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['activity' => ['name']]);

        foreach ($res->items() as &$items) {
            $items['info'] = json_decode($items['info'], true);
        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 导出
     * @return void
     * @throws Throwable
     */
    public function export(): void
    {
        list($where) = $this->queryBuilder();

        $list = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->where($where)
            ->select()
            ->toArray();


        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue([1, 1], 'ID');
        $sheet->setCellValue([2, 1], '活动名称');
        $sheet->setCellValue([3, 1], '提交内容');
        $sheet->setCellValue([4, 1], '提交时间');


        $sheet->getColumnDimension('A')->setWidth(20);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('C')->setWidth(20);
        $sheet->getColumnDimension('D')->setWidth(20);


        $h = 2;
        foreach ($list as $v) {

            $info = json_decode($v['info'],true);
            $infoData = '';
            foreach ($info as $items){
                $infoData .=$items['label'] .":".$items['value']."\n";
            }
            $sheet->setCellValue([1, $h], $v['id']);
            $sheet->setCellValue([2, $h], $v['activity']['name']);
            $sheet->setCellValue([3, $h], $infoData);
            $sheet->setCellValue([4, $h], date('Y-m-d/m/y H:i:s',$v['create_time']));

            $sheet->getStyle('C' . $h)->getAlignment()->setWrapText(true);

            $h++;
        }

        $writer = new Xlsx($spreadsheet);
        $file = time() . '.xlsx';
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Access-Control-Expose-Headers:Content-Disposition');
        header('Content-Disposition: attachment;filename=' . $file);
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}